package com.atlzk.group.order.service.impl;

import com.atlzk.common.utils.*;
import com.atlzk.group.order.dao.GroupDao;
import com.atlzk.group.order.entity.GroupEntity;
import com.atlzk.group.order.feign.TgouFeignService;
import com.atlzk.group.order.feign.UserFeignService;
import com.atlzk.group.order.utils.AlipayTemplate;
import com.atlzk.group.order.utils.IdWorker;
import com.atlzk.group.order.vo.PayVo;
import com.atlzk.group.tgou.entity.KanshopEntity;
import com.atlzk.group.tgou.entity.MiaoShopEntity;
import com.atlzk.group.tgou.entity.ResultMessage;
import com.atlzk.group.tgou.entity.TgouEntity;
import com.atlzk.group.user.entity.UserEntity;
import com.mysql.cj.util.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.atlzk.group.order.dao.OrderDao;
import com.atlzk.group.order.entity.OrderEntity;
import com.atlzk.group.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;


@Service("orderService")
@Slf4j
public class OrderServiceImpl extends ServiceImpl <OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private UserFeignService userFeignService;

    @Autowired
    private TgouFeignService tgouFeignService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private GroupDao groupDao;

    @Autowired
    private KanServiceImpl kanService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public PageUtils queryPage(Map <String, Object> params, Long umsUserId) {
        IPage <OrderEntity> page = this.page(
                new Query <OrderEntity>().getPage(params),
                new QueryWrapper <OrderEntity>().eq("ums_user_id", umsUserId)
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map <String, Object> params) {
        IPage <OrderEntity> page = this.page(
                new Query <OrderEntity>().getPage(params),
                new QueryWrapper <OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void payMoney(OrderEntity order) throws Exception {

        Long ghroupId = order.getOmsGroupId();
        GroupEntity group = groupDao.selectById(ghroupId);
        if (group.getOmsGroupStatus() == 2 || group.getOmsGroupStatus() == 3) {
            System.out.println("该团已过期或你墨迹了-》团已满员");
            return;
        }
        //查找用户信息
        UserEntity userEntity = userFeignService.findUserByUserId(order.getUmsUserId());
        Integer omsOrderNum = order.getOmsOrderNum();//商品数量
        BigDecimal money = new BigDecimal(0);
        if (order.getSmsTgouId() != null) {
            BigDecimal smsTgouPrice = order.getSmsTgouPrice();
            money = smsTgouPrice.multiply(BigDecimal.valueOf(omsOrderNum));
        } else if (order.getPmsProductId() != null) {
            BigDecimal pmsProductPrice = order.getPmsProductPrice();
            money = pmsProductPrice.multiply(BigDecimal.valueOf(omsOrderNum));
        }
        if (money.compareTo(userEntity.getUmsUserMoney()) == -1) {
            //余额足够  进行扣款
            userEntity.setUmsUserMoney(userEntity.getUmsUserMoney().subtract(money));
            userFeignService.update(userEntity);
            //扣款成功  补全订单信息  并  修改订单状态 and  开团状态  开团成功
            order.setOmsOrderPayMoney(money);
            Date now = new Date();
            order.setOmsOrderPayDate(now);
            order.setOmsOrderAddDate(now);
            order.setOmsOrderStatus(1);
            baseMapper.updateById(order);
            //开团信息
            GroupEntity groupEntity = groupDao.selectById(order.getOmsGroupId());
            if (groupEntity.getSmsTgouGroupNum() > groupEntity.getOmsGroupPersonNum()) {

                groupEntity.setOmsGroupPersonNum(groupEntity.getOmsGroupPersonNum() + 1);
            }
            //如果是最后一名成员 修改状态为 待发货
            //order  状态 0.代付款 1.拼团中 2.待发货 3.拼团失败
            //group 状态 0:未进行  1.拼团中 2.拼团成功 3.拼团失败
            if (groupEntity.getSmsTgouGroupNum() == groupEntity.getOmsGroupPersonNum()) {
                // 达到2.拼团成功标准
                groupEntity.setOmsGroupStatus(2);
                groupDao.updateById(groupEntity);
                //  需要查询该团所有订单修改    所有订单 状态 2.待发货
                Long omsGroupId = groupEntity.getOmsGroupId();
                List <OrderEntity> orderList = baseMapper.selectList(new QueryWrapper <OrderEntity>().eq("oms_group_id", omsGroupId));
                for (OrderEntity orderEntity : orderList) {
                    orderEntity.setOmsOrderStatus(2);
                    baseMapper.updateById(orderEntity);
                    //商品库存减少   库存 - 1 的 成团人数   循环次数就是订单购买数
                    Long smsTgouId = order.getSmsTgouId();
                    TgouEntity tgouEntity = tgouFeignService.byTgouId(smsTgouId);
                    tgouEntity.setSmsTgouRepertory(tgouEntity.getSmsTgouRepertory() - 1);
                    tgouFeignService.update(tgouEntity);
                }
            } else {
                //如果是还没开团  那么开团
                if (groupEntity.getOmsGroupStatus() == 0) {
                    groupEntity.setOmsGroupStatus(1);
                }
                groupDao.updateById(groupEntity);
            }
        } else {
            //余额不足
            throw new Exception("余额不足");
        }
    }

    @Override
    public void joinTgou(GroupEntity groupEntity, String umsUserId) {
        //查询商品信息
        R r = tgouFeignService.byId(groupEntity.getSmsTgouId());
        Object tgou = r.get("tgou");
        HashMap <String, Object> map = (HashMap <String, Object>) tgou;
        //完善订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOmsOrderId(idWorker.nextId());
        orderEntity.setUmsUserId(Long.valueOf(umsUserId));
        orderEntity.setOmsIsHeader(0);
        orderEntity.setSmsTgouId(groupEntity.getSmsTgouId());
        orderEntity.setOmsGroupId(groupEntity.getOmsGroupId());
        orderEntity.setPmsProductName((String) map.get("pmsProductName"));
        BigDecimal smsTgouPrice = ObjectToBigDecimalUtils.getBigDecimal(map.get("smsTgouPrice"));
        orderEntity.setSmsTgouPrice(smsTgouPrice);
        orderEntity.setOmsOrderNum(1);
        Date now = new Date();
        orderEntity.setOmsCreateDate(now);
        orderEntity.setOmsOrderStatus(0);
        baseMapper.insert(orderEntity);
    }

    @SneakyThrows
    @Override
    public String zfbPayMoney(OrderEntity order) {
        PayVo payVo = new PayVo();
        payVo.setOut_trade_no(order.getOmsOrderId() + "");
        payVo.setBody(order.getPmsProductName());
        payVo.setSubject(order.getPmsProductName());

        if (order.getSmsTgouId() != null && order.getSmsTgouId() > 0) {
            //团购商品
            payVo.setTotal_amount(order.getSmsTgouPrice().multiply(new BigDecimal(order.getOmsOrderNum())) + "");
        } else if (order.getSmsKanshopId() != null && order.getSmsKanshopId() > 0) {
            //砍价商品
            payVo.setTotal_amount(order.getSmsKanshopMinPrice().multiply(new BigDecimal(order.getOmsOrderNum())) + "");
        } else if (order.getSmsMshopId() != null && order.getSmsMshopId() > 0) {
            //秒杀商品
            payVo.setTotal_amount(order.getSmsMshopPrice().multiply(new BigDecimal(order.getOmsOrderNum())) + "");
        } else {
            //普通商品
            payVo.setTotal_amount(order.getPmsProductPrice().multiply(new BigDecimal(order.getOmsOrderNum())) + "");
        }
        String pay = alipayTemplate.pay(payVo);
        return pay;
    }


    /**
     * 限时购一件
     */
    public int astrict(Long umsUserId, Long smsTgouId, Integer smsTgouNum) {
        List <OrderEntity> orderEntityList = baseMapper.selectList(new QueryWrapper <OrderEntity>().eq("ums_user_id", umsUserId).eq("sms_tgou_id", smsTgouId));
        if (orderEntityList.size() < smsTgouNum) {
            return 1;
        }
        return 0;
    }

    @Override
    public void openkan(KanshopEntity kanshopEntity, String umsUserId) {
        //1.创建订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOmsOrderId(idWorker.nextId());
        orderEntity.setUmsUserId(Long.valueOf(umsUserId));
        orderEntity.setPmsProductId(kanshopEntity.getPmsProductId());
        orderEntity.setPmsProductName(kanshopEntity.getPmsProductName());
        orderEntity.setPmsProductPrice(kanshopEntity.getPmsProductPrice());
        orderEntity.setOmsOrderNum(1);
        orderEntity.setOmsOrderStatus(7);//第一刀之后修改为拼团中
        orderEntity.setSmsKanshopId(kanshopEntity.getSmsKanshopId());
        //结束时间
        Date date = new Date();
        DateUtil dateUtil = new DateUtil(date, DateUtil.COMMON_PATTERN);
        dateUtil.addMinute(kanshopEntity.getSmsKanshopKanDate());
        orderEntity.setOmsKanOverDate(dateUtil.toDate());
        orderEntity.setOmsCreateDate(date);
        orderEntity.setSmsKanshopDaoNum(kanshopEntity.getSmsKanshopDaoNum());
        orderEntity.setOmsKanDaoNum(0);
        orderEntity.setOmsOrderKanMoney(kanshopEntity.getPmsProductPrice());
        orderEntity.setSmsKanshopMinPrice(kanshopEntity.getSmsKanshopMinPrice());
        baseMapper.insert(orderEntity);

        //第一刀 自己砍价

        kanService.kan(orderEntity);

    }

    /**
     * 项目初始化
     *
     * @return
     */
    @PostConstruct
    public void init() {
        List <MiaoShopEntity> miaoShopEntities = tgouFeignService.miaoShoplist();
        miaoShopEntities.forEach(miaoShopEntity -> {
            redisTemplate.opsForValue().set("miaoshop_"+miaoShopEntity.getSmsMshopId(),miaoShopEntity);
            stringRedisTemplate.opsForValue().set("miaoshop_repertory"+miaoShopEntity.getSmsMshopId(),miaoShopEntity.getSmsMshopRepertory().toString());
        });
    }


    @Override
    @Transactional
    public ResultMessage miao(MiaoShopEntity miaoShopEntity, String umsUserId) {

        Long decrement = redisTemplate.opsForValue().decrement("miaoshop_repertory" + miaoShopEntity.getSmsMshopId());
        if (decrement<0){

            return new ResultMessage(false, "库存不足");
        }
//        MiaoShopEntity miaoShop = null;
//        String repertory = null;
//        if (miaoShopEntity.getSmsMshopId() != null) {
            //从redis  获取商品详情
        MiaoShopEntity miaoShop = (MiaoShopEntity) redisTemplate.opsForValue().get("miaoshop_" + miaoShopEntity.getSmsMshopId());
            //从redis  获取库存信息
        String  repertory =  stringRedisTemplate.opsForValue().get("miaoshop_repertory" + miaoShopEntity.getSmsMshopId());
//        }
        /*if (StringUtils.isNullOrEmpty(miaoShop.toString())) {//redis中是否存在秒杀商品信息  ——》redis 定时存储
            return new ResultMessage(false, "秒杀结束");
        }*/
        //判断当前商品正在秒杀
        if (miaoShop.getSmsMshopStatus() == 2) {
            //1.判断是否有库存
            if (Integer.parseInt(repertory) > 0) {
                //查询当前用户 购买当前商品的次数  以及  避免退款情况  只查询有效订单
                /*List <OrderEntity> orderEntityList = baseMapper.selectList(
                        new QueryWrapper <OrderEntity>().eq("sms_mshop_id", miaoShop.getSmsMshopId()).eq("ums_user_id", umsUserId).in("oms_order_status", 1, 3)//状态 1 待付款  2.待发货
                );*/
                //2.检查当前用户是否秒杀过  并且有没有超过限量
                /*if (orderEntityList.size() < miaoShop.getSmsMshopXianliang()) {*/
                    //3.生成订单详情  生成秒杀·订单  代付款
                    OrderEntity orderEntity = new OrderEntity();
                    orderEntity.setOmsOrderId(idWorker.nextId());
                    orderEntity.setUmsUserId(Long.valueOf(umsUserId));
                    orderEntity.setPmsProductId(miaoShop.getPmsProductId());
                    orderEntity.setPmsProductName(miaoShop.getPmsProductName());
                    orderEntity.setPmsProductPrice(miaoShop.getPmsProductPrice());
                    orderEntity.setOmsOrderNum(1);
                    orderEntity.setOmsCreateDate(new Date());
                    orderEntity.setOmsOrderStatus(1);
                    orderEntity.setSmsMshopId(miaoShop.getSmsMshopId());
                    orderEntity.setSmsMshopPrice(miaoShop.getSmsMshopPrice());
                    //创建订单
                    baseMapper.insert(orderEntity);
                    //商品库存减少
                    //redis 库存减少

                    //数据库数据更新
                    R r = updateMshopRepertory(miaoShop);

                    return new ResultMessage(true, "订单创建成功");
                /*} else {
                    //秒杀过  并且达到限量
                    return new ResultMessage(false, "达到购买限量");
                }*/
            } else {
                //库存不足
                return new ResultMessage(false, "库存不足");
            }
        } else {
            return new ResultMessage(false, "活动还未开始或已经接结束");
        }
    }

    public R updateMshopRepertory(MiaoShopEntity miaoShopEntity) {
        R update = tgouFeignService.subtractRepertory(miaoShopEntity);
        return update;
    }


    /**
     * 定时器  实现定时商品上架
     *
     */
//    @Scheduled(cron ="0 * 3 * * ?")
//    public void uploadSeckillSkulatest3Days(){
//        log.info("商品上架");
//        RLock lock = redissonClient.getLock(upload_lock);
//        lock.lock(10, TimeUnit.SECONDS);
//        try{
//            seckillService.uploadSeckillSkuLatest3Days();
//        }finally {
//            lock.unlock();
//        }
//
//    }

}